import numpy as np
import random
from threading import Lock


class VibrationSensor:
    def __init__(self, id):
        self.id = id
        self.vibration_data = []
        self.lock = Lock()

    def collect_data(self, is_attacked):
        if is_attacked:
            data = random.uniform(0.6, 1)
        else:
            data = random.uniform(0, 0.6)
        with self.lock:
            self.vibration_data.append(data)


class MotorEquipment:
    def __init__(self, sensors, is_attacked):
        self.sensors = sensors
        self.is_attacked = is_attacked


def randomly_switch_sensors(motor):
    for sensor in motor.sensors:
        sensor.collect_data(motor.is_attacked)


def simulate_normal_operation(motor, duration):
    for _ in range(duration):
        randomly_switch_sensors(motor)


def calculate_similarity(sensor, num_groups):
    data = np.array(sensor.vibration_data[-num_groups:])
    return np.corrcoef(data)


def main():
    num_sensors = 10
    sensors = [VibrationSensor(i) for i in range(num_sensors)]
    motor = MotorEquipment(sensors, False)

    normal_duration = 100
    attack_duration = 10
    attack_signal = 5

    # 模拟正常运行阶段
    simulate_normal_operation(motor, normal_duration)

    # 模拟恶意攻击阶段
    motor.is_attacked = attack_signal
    simulate_normal_operation(motor, attack_duration)

    # 计算相似度
    num_groups = 5  # 连续几组振动加速度信号
    similarities = [calculate_similarity(sensor, num_groups) for sensor in motor.sensors]

    threshold = 0.55

    results = {"相似": 0, "被干扰": 0}
    for similarity in similarities:
        if similarity <= threshold:
            results["相似"] += 1
        else:
            results["被干扰"] += 1

    return results


if __name__ == "__main__":
    results = main()

    print("\nResults:")
    print("相似: ", results["相似"])
    print("被干扰: ", results["被干扰"])
